package lib.Com;

import java.net.*;

import lib.gui.GuiMain;

public class BroadcastListener extends Thread {
	/**
	 * The BroadcastListener builds the KnownClients list in the Container object.
	 * It needs the Container object to be started first.
	 */
	private MulticastSocket socket = null;
	private static boolean running = true;

	public BroadcastListener() {
		super("BroadcastListener");
		try {
			socket = new MulticastSocket(5004);
			InetAddress address = InetAddress.getByName("230.0.0.1");
			socket.joinGroup(address);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public void run() {
		DatagramPacket packet;
		while (running) {
			if (Container.IPlocal != null) {
				try {
					byte[] buf = new byte[256];
					packet = new DatagramPacket(buf, buf.length);
					socket.receive(packet);

					String received = new String(packet.getData(), 0, packet
							.getLength());
					String[] msgs = received.split("/");

					if (!msgs[1].equals(Container.IPlocal)) {
						KnownClient tmpClient = new KnownClient(msgs[0],
								msgs[1], msgs[2], Integer.parseInt(msgs[3]));
						if (!Container.knownClients.containsKey(msgs[0])) {
							Container.knownClients.put(msgs[0], tmpClient);
							GuiMain.addFriend(msgs[0], msgs[0]);
							Thread.sleep(500);
							new BroadcastSelf().start();
						}
					}
				} catch (Exception e) {
					if (e instanceof SocketException) {
						if (!running) {
							try {
								socket = new MulticastSocket(5004);
								InetAddress address = InetAddress
										.getByName("230.0.0.1");
								socket.joinGroup(address);
							} catch (Exception e2) {
							}
						}
					} else {
						e.printStackTrace();
					}
				}
			}
			try {
				Thread.sleep(50);
			} catch (Exception e) {
			}
			try {
				String tmpipl = InetAddress.getLocalHost().getHostAddress();
				String tmpipp = PublicIPAddress.getPublicIPAddress();
				if (!tmpipl.equals(Container.IPlocal)
						|| !tmpipp.equals(Container.IPpublic)) {
					if (!tmpipl.equals(Container.IPlocal)) {
						Container.IPlocal = tmpipl;
					} else if (!tmpipp.equals(Container.IPpublic)) {
						Container.IPpublic = tmpipp;
					}
					Thread.sleep(50);
					new BroadcastSelf().start();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void Stop() {
		running = false;
		socket.close();
	}
}